import axios from 'axios'
import store from '../store'
import router from '../router'

import {getHttpUrl} from './Https'
import {show, getSign} from './Base'

import {config} from 'assets/js/data'

/**********拦截器 ===> 请求****************/
axios.interceptors.request.use(config => {

    config.url = getHttpUrl({
        module: config.data.module,
        url: config.url
    })

    config.data = {
        ...config.data,
        token: store.state.token,
        client: 'APP',
        timestamp: new Date().getTime()
    }
    //对参数进行加密
    config.data = {
        ...config.data,
        sign: getSign(config.data)
    }

    if (config.method === 'get') {
        config.params = { ...config.data };
    }

    return config
}, error => {
    Promise.reject(error)
});

/**********拦截器 ===> 响应****************/
axios.interceptors.response.use(
    response => {
        return response.data;
    },
    error => {
        const code = error.response.data.meta.code
        const msg = error.response.data.meta.message

        if(code == config.errorCodes.NO_TOKEN) {
            //重新登录
            show(msg);
            router.push('/login');
        }

        return Promise.reject(error);
    }
);

export default axios
